import axios from 'axios'
import { VueAxios } from './axios'
import ErrorCode from '@aomi/wbs/constants/ErrorCode'
import getErrMsg from '@aomi/wbs/utils/getErrMsg'
import { Toast } from 'vant'

export const baseURL = process.env.APP_API_BASE_URL

// 创建 axios 实例
const fetch = axios.create({
  // API 请求的默认前缀
  baseURL,
  timeout: 60000 // 请求超时时间
})

// 异常拦截处理器
const errorHandler = (error) => {
  Toast({
    message: '加载超时',
    position: 'middle',
    duration: 3000
  })
  return Promise.reject(error)
}

// request interceptor
fetch.interceptors.request.use(config => {
  return config
}, errorHandler)

// response interceptor
fetch.interceptors.response.use((response) => {
  console.log(response)
  const { config, data } = response
  const { status, payload } = data
  const { successTip, failureTip = true, method = 'get' } = config
  // cookie失效，重新登录
  if (status === ErrorCode.UNAUTHORIZED) {
    localStorage.setItem('mytoken', '')
  }

  const msg = getErrMsg(data, config.prefix)
  if (ErrorCode.SUCCESS === status) {
    if (typeof successTip === 'boolean') {
      successTip && Toast({
        message: msg,
        position: 'middle',
        duration: 3000
      })
    } else if (method.toLowerCase() !== 'get') {
      Toast({
        message: msg,
        position: 'middle',
        duration: 3000
      })
    }
    return payload
  } else if (failureTip) {
    Toast({
      message: msg,
      position: 'middle',
      duration: 3000
    })
  }
  console.info(`请求处理失败: ${msg}`, payload)
  throw new Error(`请求处理失败: ${msg}`)
}, errorHandler)

const installer = {
  vm: {},
  install(Vue) {
    Vue.use(VueAxios, fetch)
  }
}

export {
  installer as VueAxios,
  fetch
}
